package com.easy.component.network.request;

import com.easy.component.network.EasyHttpManager;
import com.easy.component.network.callback.CallBack;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class Okhttp3DownloadTask {
    private String TAG = EasyHttpManager.class.getName();
    /**
     * okhttp
     */
    private OkHttpClient.Builder builder;

    public Okhttp3DownloadTask() {
        builder = new OkHttpClient.Builder()
                .connectTimeout(15, TimeUnit.SECONDS)
                .writeTimeout(20, TimeUnit.SECONDS)
                .readTimeout(20, TimeUnit.SECONDS);
    }

    /**
     * @param url            下载的链接，精确到文件
     * @param destFileDir    下载的文件储存目录
     * @param destFileName   下载文件名称（自己命名）
     * @param callBackLister 下载监听
     */
    public void download(final String url, final String destFileDir, final String destFileName, final CallBack callBackLister) {
        OkHttpClient mOkHttpClient = builder.build();
        Request request = new Request.Builder().url(url).build();
        mOkHttpClient.newCall(request).enqueue(new okhttp3.Callback() {

            @Override
            public void onFailure(Call call, IOException e) {
                callBackLister.onError();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                InputStream is = null;
                byte[] buf = new byte[2048];
                int len = 0;
                FileOutputStream fos = null;
                // 储存下载文件的目录
                File dir = new File(destFileDir);
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                File file = new File(dir, destFileName);
                try {
                    is = response.body().byteStream();
                    long total = response.body().contentLength();
                    fos = new FileOutputStream(file);
                    long sum = 0;
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                        sum += len;
                        int progress = (int) (sum * 1.0f / total * 100);
                        // 下载中更新进度条
                        callBackLister.onLoading(progress);
                    }
                    fos.flush();
                    // 下载完成
                    callBackLister.onSuccess(file.getAbsolutePath());
                } catch (Exception e) {
                    callBackLister.onError();
                } finally {
                    try {
                        if (is != null)
                            is.close();
                    } catch (IOException e) {
                    }
                    try {
                        if (fos != null)
                            fos.close();
                    } catch (IOException e) {
                    }
                }
            }
        });
    }

//    public interface OnDownloadListener {
//        /**
//         * @param file 下载成功后的文件，这里可以对这个文件做操作
//         */
//        void onDownloadSuccess(File file);
//
//        /**
//         * @param progress 下载进度
//         */
//        void onDownloading(int progress);
//
//        /**
//         * @param e 下载异常信息
//         */
//        void onDownloadFailed(Exception e);
//    }
}
